#------------------------------------------------------------------------------
# Import Library
#------------------------------------------------------------------------------

rm(list = ls())
library(LalRUtils)
libreq(
  data.table, zoo, tictoc, fixest, PanelMatch, patchwork,
  rio, magrittr, janitor, did, panelView, ggplot2, RPushbullet, ggiplot, 
  tidyverse, data.table, zoo, tictoc, fst, fixest, PanelMatch, patchwork,
  rio, magrittr, janitor, did, panelView, ggiplot, tictoc, binsreg, interflex
)

set.seed(42)
theme_set(lal_plot_theme())

notif = \(x) pbPost("note", x)

#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Define Paths
#------------------------------------------------------------------------------

# R studio
setwd( dirname(rstudioapi::getActiveDocumentContext()$path) )
# R default : unccoment if you use default R
# setwd(getSrcDirectory(function(){})[1])

#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Load Data
#------------------------------------------------------------------------------

vcf <- fread("vcf_data_complete.csv", sep = ",")
setnames( vcf, "d", "D")
vcf_data <- copy( vcf )
gfc <- fread("gfc_dta.csv" )


#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Table for figure 5: Dynamic Treatment Effects of 
#                     PESA Adoption on Forest Index
#------------------------------------------------------------------------------


if (exists("vcf_data")) {
  vcf = vcf_data[year >= 1995]
  rm(vcf_data)
}

# %% GFC
vcf[, time := year - first_pesa_exposure]
vcf[, pref_bin := ntile(cover_1990, 10)]
vcf_evsamp = vcf[time %between% c(-6, 6)]
# %%
estudy_plot = function(cutoff, title){
  es1 = feols(forest_index ~ i(time, sch,  ref=-1) | cellid + styear,
              cluster = ~ blk, vcf_evsamp[pref_bin >= cutoff])
  f = ggiplot(es1) + ylim(c(-3, 3)) + ggtitle(title) + lal_plot_theme()
  return(f)
}


ols_effect <- function(cutoff ){
  es1 = feols(forest_index ~ i(time, sch,  ref=-1) | cellid + styear,
              cluster = ~ blk, vcf_evsamp[pref_bin >= cutoff])
}

models_vcf_ev <- lapply( c(1, 6, 7, 8, 9, 10), ols_effect )
"never_treated" %in% names(vcf_evsamp)

# Function 
sum_stats_vcfevsamp = function( cutoff ){
  
  # Filter data
  dat = vcf_evsamp[ pref_bin >= cutoff ]
  dat[, never_treated := max(D) == 0, cellid]
  
  # Get control and treatment value for pre Y
  ctrl <- dat[ never_treated == 1 & year < first_pesa_exposure, 
               mean( forest_index ) ]
  treat <- dat[ never_treated == 0 & year < first_pesa_exposure, 
                mean( forest_index ) ]
  
  year_min <- min(dat$year)
  year_max <- max(dat$year)
  # return vector of values
  return( c( ctrl, treat, year_min, year_max ) )
}

# Generate sum statistics for vcfevsamp
controls_vcfevsamp <- c()
treated_vcfevsamp <- c()
min_years_vcfevsamp <- c()
max_years_vcfevsamp <- c()
vec_cutoff <- c(1, 6, 7, 8, 9, 10)
for ( i in 1:length( vec_cutoff ) ){
  res <- sum_stats_vcfevsamp( vec_cutoff[ i ] )
  controls_vcfevsamp[ i ] <- res[ 1 ]
  treated_vcfevsamp[ i ] <- res[ 2 ]
  min_years_vcfevsamp[ i ] <- res[ 3 ]
  max_years_vcfevsamp[ i ] <- res[ 4 ]
}


# All models
treatmap =c(
  "time::-6:sch" = "Lag Year 6 $\\times$ Sch",
  "time::-5:sch" = "Lag Year 5 $\\times$ Sch",
  "time::-4:sch" = "Lag Year 4 $\\times$ Sch",
  "time::-3:sch" = "Lag Year 3 $\\times$ Sch",
  "time::-2:sch" = "Lag Year 2 $\\times$ Sch",
  "time::0:sch" = "Year 0 $\\times$ Sch",
  "time::1:sch" = "Lead Year 1 $\\times$ Sch",
  "time::2:sch" = "Lead Year 2 $\\times$ Sch",
  "time::3:sch" = "Lead Year 3 $\\times$ Sch",
  "time::4:sch" = "Lead Year 4 $\\times$ Sch",
  "time::5:sch" = "Lead Year 5 $\\times$ Sch",
  "time::6:sch" = "Lead Year 6 $\\times$ Sch",
  # GFC
  "def_ha"       = "Annual Deforestation in Hectares",
  "village"      = "Village",
  "village[t]"   = "Village + Village TT",
  # VCF
  "forest_index" = "Forest cover index",
  "green_index"  = "Non-forest green index",
  "built_index"  = "Non-forest index",
  "cellid"       = "Pixel",
  "cellid[t]"    = "pixel + pixel TT",
  # both
  "yr"           = "Year",
  "year"         = "Year",
  "styear"       = "State $\\times$ Year",
  "D"            = "PESA $\\times$ Scheduled",
  "block"        = "Block",
  "blk"          = "Block"
)
fitstat_register("n_new", function(x) summary( x )$nobs , 
                 "\\# Observations")
desc = "Deforestation and Forest cover index"
fn = "figure5_regs"; lab = "tab:figure5_regs";
etable(models_vcf_ev,
       style.tex = style.tex(main = "base", 
                             depvar.title = "", 
                             model.title = "", 
                             var.title = "\\midrule", 
                             slopes.title = "\\midrule \\emph{Time Trends}", 
                             yesNo = c("$\\checkmark$", ""), 
                             signif.code = NA, 
                             tablefoot = FALSE, 
                             line.bottom = "\\midrule \\midrule"),
       signif.code = NA,
       fixef_sizes = T, 
       fixef_sizes.simplify = F,
       fitstat = c( "n_new", "r2" ), 
       tex = TRUE,
       dict = treatmap,
       label = lab,
       title = glue::glue("Dynamic Treatment Effects of 
                          PESA Adoption on Forest Index"),
       notes = "\\emph{Notes:} Standard errors are clustered at the block level and reported in parentheses.",
       extralines=list(
         "\\midrule \\emph{Summary Statistics}" = c( "", "", "", "", "", "" ),
         "Mean Pre-Y (Non-Sch)"= c( controls_vcfevsamp ),
         "Mean Pre-Y (Sch )"   = c( treated_vcfevsamp ),
         "Dataset"     = c( rep( "VCF", 6 ) ),
         "Timespan"    = c( rep( "1995-2017", 6 ) )
       ),
       file = "main_figure5_table.tex", 
       replace = TRUE
)

#------------------------------------------------------------------------------

